package ru.spbu.math.android.cbrf.dataprovider.yandex;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

import ru.spbu.math.android.cbrf.model.Rate;
import ru.spbu.math.android.cbrf.model.RateType;
import ru.spbu.math.android.cbrf.model.StockItem;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Class for parsing data from Yandex and put it in the List of Rate.
 * This class extends DefaultHandler
 */

//<sdt date="2010-07-12" time="13:15">
//	<value>1988.00</value> 
//	<change>-12.0000</change> 
//	<changeprcnt>-0.60</changeprcnt> 
//</sdt>

public class YandexSaxHandler extends DefaultHandler {
	
	private final String TAG = "YandexSaxHandler";
	
	private final String SDT = "sdt";
	private final String DATE = "date";
	private final String TIME = "time";
	private final String VALUE = "value";
//	private final String STOCK = "stock";
//	private final String ID = "id";

	private static String id = "";

	private List<Rate> rateList;

	private Rate rate;
	private StringBuilder builder;

	private StockItem source;
	private StockItem target;

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		builder.append(ch, start, length);
	}

	@Override
	public void endElement(String uri, String localName, String name)
            throws SAXException {
        if (this.rate != null) {
            if (localName.equalsIgnoreCase(VALUE)) {
            	try{
            	rate.setValue(Double.parseDouble(builder.toString()));
//            	Log.d(TAG, "builder.toString() = " + builder.toString());
//            	Log.d(TAG, "Rate.setValue");
            	}catch (Exception e){
                String str = "";
//                Log.d(TAG, "builder.toString() = " + builder.toString());
//                Log.d(TAG, "builder.toString().length()= " + builder.toString().length());
                int length = builder.toString().length();
                int k = length - 1;
                while(Character.isDigit(builder.toString().charAt(k))||
                		Character.toString(builder.toString().charAt(k)).equals(".")){
//                	Log.d(TAG, "builder.toString().charAt(k) = " + builder.toString().charAt(k));
                	k--;
                }
//                Log.e(TAG, "builder.toString().charAt(k) = " + builder.toString().charAt(k));
                for(int i = k + 1; i < length; i++){
                	str = str + builder.toString().charAt(i);
                }
//                Log.d(TAG, "value = " + str);
                rate.setValue(Double.parseDouble(str));
//                Log.d(TAG, "Rate.setValue modif");
            	}
            }else if (localName.equalsIgnoreCase(SDT)) {
                rateList.add(rate);
//                Log.d(TAG, "Add rate to rateList");
            }

            builder.setLength(0);
        }
    }

	@Override
	public void startDocument() throws SAXException {
		rateList = new ArrayList<Rate>();
		builder = new StringBuilder();
		Log.d(TAG, "Start document");
	}

	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
/*
		if (localName.equalsIgnoreCase(STOCK)) {
			id = attributes.getValue(ID);
			Log.d(TAG, "Get ID");
		} else 
		*/
			if (localName.equalsIgnoreCase(SDT)) {
			this.rate = new Rate();
			
//			Log.d(TAG, attributes.getValue(DATE) + " "
//					+ attributes.getValue(TIME));
			
			String str = attributes.getValue(DATE) + " " + attributes.getValue(TIME);
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
            Date date = new Date();
            try {
                date = df.parse(str);
            } catch (ParseException e) {
                date = Calendar.getInstance().getTime();
                Log.e(TAG, "Parse Date Exception");
            }
            rate.setDate(date);
			rate.setResource(new RateType(source, target, id));
		}
	}
	
	public List<Rate> getRateItem() {
		return rateList;
	}

	public void setRate(RateType rate) {
		this.source = rate.getSource();
		this.target = rate.getTarget();		
	}
}